package com.ocom.xcxapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.WxServiceUrl;
import com.ocom.common.entity.card.EntityXfMerchantInfo;
import com.ocom.common.entity.card.EntityXfSignNo;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.entity.master.EntityWechatAppInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.xcx.PhoneUserVo;
import com.ocom.common.request.xcx.WxFaceLoginVo;
import com.ocom.common.request.xcx.WxGetPhoneVo;
import com.ocom.common.resp.RespMachMessage;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.HttpUtils;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.PersonVo;
import com.ocom.common.vo.human.UserInfoYkmVo;
import com.ocom.redis.util.RedisUtil;
import com.ocom.xcxapi.client.CompanyClientService;
import com.ocom.xcxapi.client.HumanClientService;
import com.ocom.xcxapi.client.PayConfigClientService;
import com.ocom.xcxapi.client.PayHandleClientService;
import com.ocom.xcxapi.mq.product.ActiveQuiryProduct;
import com.ocom.xcxapi.vo.WxPhoneVo;
import com.ocom.xcxapi.vo.WxUserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 微信人脸签约
 * @Author: 朱晖
 * @Date: 2022/12/14
 **/
@Slf4j
@RestController
public class WxFaceSignController {

	@Resource
	private RedisUtil redisUtil;

	String url = "http://192.168.3.123:32880/ocom_pay/";

	@Autowired
	private HumanClientService humanClientService;
	@Autowired
	private PayConfigClientService payConfigClientService;
	@Autowired
	private CompanyClientService companyClientService;

	@Autowired
	private ActiveQuiryProduct activeQuiryProduct;

	@Autowired
	private PayHandleClientService payHandleClientService;

	/**
	 * 获取手机号
	 * 返回是否第一次签约
	 */
	@PostMapping(WxServiceUrl.URL_WxFaceGetPhone)
	public Result getWxPhone(@RequestBody WxGetPhoneVo wxGetPhoneVo) throws ParseException, IOException {
		Result result = accessToken(wxGetPhoneVo.getComId());
		if (result.getCode() != 200) {
			return result;
		}
		String wxGetPhoneUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + result.getData();

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("code", wxGetPhoneVo.getCode());
		String ss = HttpUtils.doPostBodyData(wxGetPhoneUrl, new HashMap<>(), jsonObject);

		WxPhoneVo wxPhoneVo = JSON.parseObject(ss, WxPhoneVo.class);
		if (wxPhoneVo.getErrcode() == 0) {
			Map<String, String> map = JSON.parseObject(JSON.toJSONString(wxPhoneVo.getPhone_info()), Map.class);

//			GetPersoDecryVo getPersoDecryVo = new GetPersoDecryVo();
//			getPersoDecryVo.setComId(wxGetPhoneVo.getComId());
//			getPersoDecryVo.setPPhone(map.get("phoneNumber"));
//			Result result2 = humanClientService.GetPersonInfoByPhoneOrCard(getPersoDecryVo);
			Result result4 = companyClientService.getCompanyInfoById(wxGetPhoneVo.getComId());

			RespMachMessage result2 = payHandleClientService.getPersonByPhone(wxGetPhoneVo.getComId(), map.get("phoneNumber"));
			Result result1 = null;
			Object re3 = null;
			Boolean existPerson = false;
			if (result2.getCode().equals("0000")) {
				existPerson = true;
				EntityPersonnelInfo entityPersonnelInfo = JSON.parseObject(JSON.toJSONString(result2.getData()), EntityPersonnelInfo.class);
				result1 = humanClientService.getXfUserInfo(entityPersonnelInfo.getComId(), entityPersonnelInfo.getPId());

				Result result3 = payConfigClientService.getUserPayWay(entityPersonnelInfo.getComId(), entityPersonnelInfo.getPId(), 0, 16);
				if (result3.getCode() == 200) {
					re3 = result3.getData();
				}
			}
			Map<String, Object> resMap = new HashMap<>();
			resMap.put("phone", wxPhoneVo.getPhone_info());
			resMap.put("company", result4.getData());
			resMap.put("userInfo", result2.getData());
			resMap.put("userXfInfo", null);
			if(result1!=null){
				resMap.put("userXfInfo", result1.getData());
			}
			resMap.put("sign", re3);
			resMap.put("existPerson", existPerson);
			return ResultUtil.success(resMap);
		}
		return ResultUtil.info(400, "error", wxPhoneVo);
		/**
		 * {
		 *     "errcode":0,
		 *     "errmsg":"ok",
		 *     "phone_info": {
		 *         "phoneNumber":"xxxxxx",
		 *         "purePhoneNumber": "xxxxxx",
		 *         "countryCode": 86,
		 *         "watermark": {
		 *             "timestamp": 1637744274,
		 *             "appid": "xxxx"
		 *         }
		 *     }
		 * }
		 */
	}


	/**
	 * 手机号获取人员信息
	 * 签约的token
	 *
	 * @return
	 */
	@PostMapping(WxServiceUrl.URL_WxFaceGetUser)
	public Object getUserByPhone(@RequestBody PhoneUserVo phoneUserVo) throws ParseException, IOException {

		String perSignUrl = url + "offlineFacepay/presign.do";
		//1、获取支付通道
		Result result1 = payConfigClientService.MerchPageInfo(phoneUserVo.getComId(), 0);
		log.info("公众号支付-获取支付通道参数 【{}】", result1);
		if (result1.getCode() != 200) {
			log.info("支付参数获取失败 【{}】 ", result1);
			return ResultUtil.error(ResultEnum.Err_4029);
		}
		EntityXfMerchantInfo entityXfMerchantInfo = JSONObject.parseObject(JSONObject.toJSONString(result1.getData()), EntityXfMerchantInfo.class);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("business_name", "GROUP_DINING");
		jsonObject.put("out_user_id", phoneUserVo.getPhone());
		jsonObject.put("company_id", entityXfMerchantInfo.getCompanyId());
		jsonObject.put("password", entityXfMerchantInfo.getPassword());
		jsonObject.put("user_name", entityXfMerchantInfo.getUserName());
		jsonObject.put("phone", phoneUserVo.getPhone());
		String ss = HttpUtils.doPostBodyData(perSignUrl, new HashMap<>(), jsonObject);


		phoneUserVo.setCompany_id(entityXfMerchantInfo.getCompanyId());
		phoneUserVo.setUser_name(entityXfMerchantInfo.getUserName());
		phoneUserVo.setPassword(entityXfMerchantInfo.getPassword());
		phoneUserVo.setOut_user_id(phoneUserVo.getPhone());
		activeQuiryProduct.sendDelayMessage(JSON.toJSONString(phoneUserVo));

		log.info("微信人脸签约 【{}】 【{}】", jsonObject, ss);
		return ss;
	}


	//微信人脸回调
	@PostMapping(WxServiceUrl.URL_WxCallback)
	public Object WxCallback(@RequestBody PhoneUserVo phoneUserVo) {
		return "succ";
	}


	//微信人脸回调
	@PostMapping(WxServiceUrl.URL_WxDelSign)
	public Object WxDelSign(@RequestBody PhoneUserVo phoneUserVo) throws ParseException, IOException {

		//1、获取支付通道
		Result result1 = payConfigClientService.MerchPageInfo(phoneUserVo.getComId(), 0);
		log.info("公众号支付-获取支付通道参数 【{}】", result1);
		if (result1.getCode() != 200) {
			log.info("支付参数获取失败 【{}】 ", result1);
			return ResultUtil.error(ResultEnum.Err_4029);
		}
		EntityXfMerchantInfo entityXfMerchantInfo = JSONObject.parseObject(JSONObject.toJSONString(result1.getData()), EntityXfMerchantInfo.class);

		String url = "http://192.168.3.123:32880/ocom_pay/offlineFacepay/user/select.do";

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("company_id", entityXfMerchantInfo.getCompanyId());
		jsonObject.put("password", entityXfMerchantInfo.getPassword());
		jsonObject.put("user_name", entityXfMerchantInfo.getUserName());
		jsonObject.put("mchId", "");
		jsonObject.put("out_user_id", phoneUserVo.getPhone());
//		jsonObject.put("out_user_id", phoneUserVo.getPId());
		String ss = HttpUtils.doPostBodyData(url, new HashMap<>(), jsonObject);

		Result result = JSONObject.parseObject(ss, Result.class);
		if (result.getCode() == 200) {
			WxUserInfoVo wxUserInfoVo = JSONObject.parseObject(JSON.toJSONString(result.getData()), WxUserInfoVo.class);
			log.info("微信人脸签约查询结果1 【{}】 ", wxUserInfoVo);
			if (!wxUserInfoVo.getFace_image_ok()) {
				EntityXfSignNo entityXfSignNo = new EntityXfSignNo();
				entityXfSignNo.setComId(phoneUserVo.getComId());
				entityXfSignNo.setMerchId(0);
				entityXfSignNo.setPayWay(16);
				entityXfSignNo.setPId(phoneUserVo.getPId());
				payConfigClientService.delUserSign(entityXfSignNo);
				return ResultUtil.success();
			}

			String delUrl = "http://192.168.3.123:32880/ocom_pay/offlineFacepay/termination.do";

			JSONObject jsonObject1 = new JSONObject();
			jsonObject1.put("company_id", entityXfMerchantInfo.getCompanyId());
			jsonObject1.put("password", entityXfMerchantInfo.getPassword());
			jsonObject1.put("user_name", entityXfMerchantInfo.getUserName());
			jsonObject1.put("mchId", "");
			jsonObject1.put("user_id", wxUserInfoVo.getUser_id());
			String ss3 = HttpUtils.doPostBodyData(delUrl, new HashMap<>(), jsonObject1);

			Result result3 = JSONObject.parseObject(ss3, Result.class);
			//解约
			if (result3.getCode() == 200) {
				EntityXfSignNo entityXfSignNo = new EntityXfSignNo();
				entityXfSignNo.setComId(phoneUserVo.getComId());
				entityXfSignNo.setMerchId(0);
				entityXfSignNo.setPayWay(16);
				entityXfSignNo.setPId(phoneUserVo.getPId());
				payConfigClientService.delUserSign(entityXfSignNo);
				return ResultUtil.success();
			}
			return ss3;
		} else {
			return ss;
		}
	}


	//解约
//https://api.mch.weixin.qq.com/v3/offlinefacemch/organizations/{organization_id}/users/user-id/{user_id}/terminate-contract


	//获取小程序token
	public Result accessToken(Long comId) {
		if (comId == null) {
			return null;
		}
		Object er = redisUtil.get("XcxAccessToken:comId:" + comId);
		if (er != null) {
			String token = (String) er;
			return ResultUtil.success(token);
		}

		Result result = payConfigClientService.getWxInfo(comId, 0l, "xcx");
		if (result.getCode() != 200) {
			return result;
		}
		EntityWechatAppInfo entityWechatAppInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityWechatAppInfo.class);
		String wxTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + entityWechatAppInfo.getAppid() + "&secret=" + entityWechatAppInfo.getAppsecret();

		Map<String, Object> map = HttpUtils.doGet(wxTokenUrl);

		String token = (String) map.get("access_token");
		redisUtil.set("XcxAccessToken:comId:" + comId, token, 5400l);
		return ResultUtil.success(token);
	}


	//微信人脸登录
//	@PreAuthorize("hasRole('ROLE_XCX')")
	@PostMapping(WxServiceUrl.URL_wxFaceLogin)
	public Object wxFaceLogin(@RequestBody WxFaceLoginVo wxFaceLoginVo) {
		Map<String, Object> map3 = new HashMap<>();
		map3.put("comId", wxFaceLoginVo.getComId());
		map3.put("pName", wxFaceLoginVo.getPName());
		map3.put("pCode", wxFaceLoginVo.getPCode());
		map3.put("page", 1);
		map3.put("size", 1);
		Result result2 = humanClientService.PersonnelGetPersonInfo(map3);
		if (result2.getCode() != 200) {
			return result2;
		}
		String list = JSON.parseObject(JSON.toJSONString(result2.getData())).get("list").toString();
		List<UserInfoYkmVo> userInfoYkmVos = JSON.parseArray(list, UserInfoYkmVo.class);

		if (userInfoYkmVos.size() > 0) {
			UserInfoYkmVo userInfoYkmVo = userInfoYkmVos.get(0);

			if(!userInfoYkmVo.getPPwd().equals(wxFaceLoginVo.getPPwd())){
				return ResultUtil.error(ResultEnum.Err_311);
			}

			Object re3 = null;
			Result result3 = payConfigClientService.getUserPayWay(wxFaceLoginVo.getComId(), userInfoYkmVo.getPId(), 0, 16);
			if (result3.getCode() == 200) {
				//有签约的话  不能更换手机号
				return ResultUtil.error(ResultEnum.Err_2039);
//				re3 = result3.getData();
			}

			//更新人员手机号
			PersonVo personVo = new PersonVo();
			personVo.setComId(wxFaceLoginVo.getComId());
			personVo.setPId(userInfoYkmVo.getPId());
			personVo.setPPhone(wxFaceLoginVo.getPhone());
			Result result = humanClientService.UpdatePerson(personVo);
			if (result.getCode() != 200) {
				return ResultUtil.error(ResultEnum.Err_2038);
			}
			userInfoYkmVo.setPPhone(wxFaceLoginVo.getPhone());

			Result result4 = companyClientService.getCompanyInfoById(wxFaceLoginVo.getComId());
			Result result1 = humanClientService.getXfUserInfo(wxFaceLoginVo.getComId(), userInfoYkmVo.getPId());


			Map<String, Object> resMap = new HashMap<>();
			resMap.put("phone", wxFaceLoginVo.getPhone());
			resMap.put("company", result4.getData());
			resMap.put("userInfo", userInfoYkmVo);
			resMap.put("userXfInfo", result1.getData());
			resMap.put("sign", null);
			return ResultUtil.success(resMap);
		}
		return ResultUtil.error(ResultEnum.Err_4017);


	}


}
